import websocket from "@/utils/websocket";
import APP_CONFIG from "@/config/config";

var  baseUrl = APP_CONFIG.VUE_APP_API_HOST_DEFAULT

//带Token请求
const httpTokenRequest = (opts) => {
    let token = uni.getStorageSync("javawebtoken");
    let header = {
        'Authorization': token,
    }
    if (opts.noToken){
        header = {}
    }
    let promise = new Promise(function(resolve, reject) {
        uni.showLoading({
            title: '加载中',
            mask: true
        })
        uni.request({
            url: baseUrl + opts.url,
            data: opts.method === 'get' ? opts.params : opts.data,
            method: opts.method,
			sslVerify: false,
            header: {
                'X-Requested-With': 'XMLHttpRequest',
                "Accept": "application/json",
                'Content-Type': opts.contentType ? opts.contentType : 'application/json;charset=UTF-8',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Headers': '*',
                ...header
            },
            dataType: 'json',
            success(response) {
                console.log(response.data)

                if (response.data.code === "110") {
                    //登录成功
                    if (response.header && (response.header.Authorization || response.header.authorization)) {
                        uni.setStorageSync('javawebtoken', response.header.Authorization ? response.header.Authorization : response.header.authorization)
                        // websocket.connectWebsocket()
                    }
                } else if (response.data.code === "106" || response.data.code === "115" || (!uni.getStorageSync("javawebtoken") && response.header.Authorization)) {
                    uni.setStorageSync('javawebtoken', response.header.Authorization)
                    //用户未登录
                    uni.reLaunch({
                        url: 'login'
                    })
                    // websocket.closeWebSocket()
                }
                resolve(response.data);
            },
            fail(err) {
                setTimeout(function (){
                    uni.showToast({icon: "none",title: '服务响应失败'});
                },500)
                console.error(err);
                reject(err);
            },
            complete() {
            }

        })

        uni.hideLoading();
    })
    return promise
};

export default httpTokenRequest

